#!/bin/bash

if [ "x$1" \= "x" ]
then source /etc/nstat.conf || exit 1
else source $1 || exit 1
fi

[ "x${nstat_enable}" = "xNO" ] && exit 0

starttime=`date +%s`

# Сегодяшний день
day="`date +%Y-%m-%d`"
# Текущий год
year="`date +%Y`"
# Текущий месяц
month="`date +%m`"
curr_time="`date +%H:%M:%S`"

##################################
##################################
##################################

if [ -e ${pidfile} ]
then
 if kill -0 `cat ${pidfile}`
 then
  date >&2
  echo "I'm already running now... try later, please." >&2
  exit 1
 fi
 date >&2
 echo "Invalid pidfile? ${pidfile}" >&2
fi

echo $$ >${pidfile}

if !(kill -s SIGTSTP `cat ${counter_pid}`)
then
 echo "${counter_name} is not running?">&2; exit 1
else
 echo -n "Wait for ${counter_name}... "
 sleep 1
 echo "done"
 mv ${counter_file} ${counter_tmpfile}
 kill -s SIGCONT `cat ${counter_pid}`
fi

mkdir -p ${trafdir}
traflogfile="${trafdir}/${day}.log"

echo `wc -ml ${counter_tmpfile}`

cat ${counter_tmpfile} >> ${traflogfile}

# снимаем с баланса некоторые суммы....
# ${pyscript} правит таблицу traffic_tmp (platno, oplacheno)
# и users - снимает деньги с баланса
# и затем переносит данные из traffic_tmp в traffic

cd ${pyscriptdir}
echo -n 'Run python update script: '
python ${pyscript}

# Очищаем файл c логами
rm -f ${counter_tmpfile}

# # и заодно обновляем правила rc.fw, если необходимо
# if !(/usr/bin/diff /etc/rc.provide /etc/rc.provide.old >/dev/null)
# then
#  echo "/etc/rc.provide changed => /etc/rc.fw && cp /etc/rc.provide /etc/rc.provide.old"
#  /etc/rc.fw >/dev/null
#  cp /etc/rc.provide /etc/rc.provide.old
# fi

finishtime=`date +%s`
let dt=$finishtime-$starttime >/dev/null
ndt="[$day $curr_time]: executed $dt seconds."
echo "Finished after $dt seconds."
echo $ndt >>${logfile}


rm ${pidfile}
date +'%H:%M:%S' >/var/nauth-last-update
